//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    logo:'',
     array:["中国","美国","巴西","日本"],  
    toast1Hidden:true,  
    modalHidden: true,  
    modalHidden2: true,  
    notice_str: '',  
    index:0 , 
    imageWidth:250,
    imageHeight:250,
    photoList:[],
    reply: [
      {name: 'false', value: '否'},
      {name: 'true', value: '是', checked: 'true'},
    ] 
  },
  radioChange: function(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.data.reply = e.detail.value
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    console.log('onLoad')
    var that = this
    //调用应用实例的方法获取全局数据
    app.getUserInfo(function(userInfo){
      //更新数据
      that.setData({
        userInfo:userInfo,
        logo:userInfo.avatarUrl
      })
    })
  },

  toast1Change:function(e){  
    this.setData({toast1Hidden:true});  
  },  
  //弹出确认框  
  modalTap: function(e) {  
    this.setData({  
      modalHidden: false  
    })  
  },  
  confirm_one: function(e) {  
    console.log(e);  
    this.setData({  
      modalHidden: true,  
      toast1Hidden:false,  
      notice_str: '提交成功'  
    });
    wx.redirectTo({
       url:'../logs/logs'
     })  
  },  
  cancel_one: function(e) {  
    console.log(e);  
    this.setData({  
      modalHidden: true,  
      toast1Hidden:false,  
      notice_str: '取消成功'  
    });  
  },  
  //弹出提示框  
  modalTap2: function(e) {  
    this.setData({  
      modalHidden2: false  
    })  
  },  
  modalChange2: function(e) {  
    this.setData({  
      modalHidden2: true  
    })  
  },  
  bindPickerChange: function(e) {  
    console.log('picker发送选择改变，携带值为', e.detail.value)  
    this.setData({  
      index: e.detail.value  
    })  
  },  
 
  formSubmit: function(e) {  
    var that = this;  
    var formedData = e.detail.value;  
     console.log(getApp().globalData.userInfo);
    var tempFilePaths  =   that.data.photoList; 
//      upload_files( tempFilePaths,  formedData, 
// function(res){
//       console.log(res);
//       that.modalTap();
//     },
//     function(){
//     }) 
    var successUp = 0; //成功个数
    var failUp = 0; //失败个数
    var length =tempFilePaths.length; //总共个数
    var i = 0; //第几个
    if(length !=0){
      upload_file( tempFilePaths,formedData, successUp,failUp,i,length);
    }
    else{
       wx.request({  
        url: 'https://www.brcms.cn/bryx/form/Index',
        method: "GET",   
        data: {
          username:formedData.username,
          phone:formedData.phone,
          reply: formedData.reply,
          count: i+1,
          end: length,
          code: getApp().globalData.code,
          encryptedData: getApp().globalData.encryptedData,
          iv: getApp().globalData.iv,
          latitude: getApp().globalData.latitude,
          longitude: getApp().globalData.longitude,
        },  
        header: {  
            'Content-Type': 'application/json'  
        },  
        success: function(res) {  
        console.log(res.data)  
          that.modalTap();  
        }  
      })  
    }
     
  },  
  formReset: function() {  
    console.log('form发生了reset事件');  
    this.modalTap2();  
  },

  chooseImageTap: function(){
    let _this = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#f7982a",
      success: function(res) {
        if (!res.cancel) {
          console.log('res.tapIndex'+res.tapIndex);  
          if(res.tapIndex == 0){
            _this.chooseWxImage('album')
          }else if(res.tapIndex == 1){
            _this.chooseWxImage('camera')
          }
        }
      }
    })

  },
  chooseWxImage:function(type){
    let _this = this;
    var that = this;
    var showFileList = that.data.photoList;
    wx.chooseImage({
    sizeType: ['original', 'compressed'],
    sourceType: [type],
    success: function (res) {
      // console.log(res);
      // _this.setData({
      //   logo: res.tempFilePaths[0],
      // });
       // 后台慢慢保存文件到本地      
            res.tempFilePaths.forEach(function(tempFilePath){
                // 调用保存到本地的API
                wx.saveFile({
                  tempFilePath: tempFilePath,
                  success: function(res){
                    console.log("保存到本地的文件路径："+res.savedFilePath);
                    showFileList.push(res.savedFilePath);
                    // 更新页面显示
                    console.log(showFileList.length+"个展示图片");
                    that.setData({
                        photoList:showFileList
                    });
                  },
                  fail: function () {
                    // fail
                    console.log('saveFile fail');
                  }
                })
            }); 
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        //var tempFilePaths = res.tempFilePaths;
        //upload(that, tempFilePaths);
    },
     fail: function () {
        // fail
        console.log('fail');
      }
    })
  }
 
})



function upload_file( tempFilePaths, formedData,  successUp, failUp,i,length) {
console.log('a='+tempFilePaths[i])
wx.uploadFile({
  url: 'https://www.brcms.cn/bryx/form/Index',
  filePath:tempFilePaths[i],
   name: 'file',
    header: {
        'content-type':'multipart/form-data'
    }, // 设置请求的 header
    formData:{
      username:formedData.username,
      phone:formedData.phone,
      reply: formedData.reply,
      count: i+1,
      end: length,
      latitude: getApp().globalData.latitude,
      longitude: getApp().globalData.longitude,
    }, // HTTP 请求中其他额外的 form data
    // success: function(res){
    //   // console.log(res);
    //   if(res.statusCode ==200 && !res.data.result_code){
    //       typeof success == "function" && success(res.data);
    //   }else{
    //       typeof fail == "function" && fail(res);
    //   }
    // },
    // fail: function(res) {
    //     console.log(res);
    //   typeof fail == "function" && fail(res);
    //         },
    success: function(res){
        console.log('成功'+successUp+res.data);
        successUp++;
    },
    fail: () => {
        failUp ++;
    },
    complete: () => {
      i ++;                        
      if(i == length)
      {                      

        console.log('总共'+successUp+'张上传成功,'+failUp+'张上传失败！');
        //this.confirm_one();
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 2000
        })
        wx.redirectTo({
          url:'../logs/logs'
        })

      }
      else
      {  //递归调用uploadDIY函数
          upload_file(tempFilePaths,formedData, successUp,failUp,i,length);
      }
    },
   
  })
}


